package net.core.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.core.base.dao.CommonDAO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SysConfigUtil {

	private static final Log logger = LogFactory.getLog(SysConfigUtil.class);

	private static Map<String, Map<String, String>> mapAll = new HashMap<String, Map<String, String>>();

	private static CommonDAO commonDAO = (CommonDAO) SpringContext.getBean("commonDAO");

	public static String getConfigValue(String key, String group) {
		logger.debug("获取系统参数，group:" + group + ";key:" + key);
		String result = "";
		boolean bool = false;
		if (null == group || "".equals(group)) {
			logger.error("分组为空，请确认是否配置？分组：" + group + "。");
			return "";
		}
		if (null == key || "".equals(key)) {
			logger.error("参数为空，请确认是否配置？参数：" + key + "。");
			return "";
		}
		result = getValue(key, group);
		logger.info("系统参数值，group:" + group + ";key:" + key + ";value:" + result+";");
		return result;
	}

	private static String getValue(String key, String group) {
		String result = "";
		Map<String, String> map = getGroupMap(group);
		if (null != map && map.size() > 0) {
			result = map.get(key);
			if (null == result || "".equals(result)) {
				map = getGroupValues(group);
				result = map.get(key);
			}
		} else {
			logger.error("分组未配置，分组：" + group + "。");
		}
		if (null == result) {
			logger.error("参数未配置，分组：" + group + ",参数：" + key + "。");
			result = "";
		}

		return result;
	}

	public static Map<String, String> getGroupMap(String group) {
		Map<String, String> map = new HashMap<String, String>();
		// 判断mapAll中是否存在group的分组，如果不存在就从数据库中获取。存在，直接返回。
		if (null == mapAll.get(group)) {
			map = getGroupValues(group);
		} else {
			map = mapAll.get(group);
		}
		return map;
	}

	private static Map<String, String> getGroupValues(String group) {
		logger.info("初始化分组：" + group);
		Map<String, String> map = new HashMap<String, String>();
		String sql = "select * from s_sysconfig t where t.enabled='1' and t.sc_group='" + group
				+ "'";
		logger.debug("初始化语句：" + sql);
		try {
			List<HashMap> list = commonDAO.getDataList(sql);
			if (null != list && list.size() > 0) {
				for (HashMap mapData : list) {
					map.put(StrUtils.getNotNullStrValue(mapData.get("SC_NAME")),
							StrUtils.getNotNullStrValue(mapData.get("SC_VALUE")));
				}
				logger.debug("分组数量：" + map.size());
				mapAll.put(group, map);
				logger.debug("分组总数：" + mapAll.size());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

}
